package com.anyonavinfo.cpaddemo.view.mainview.applist;


import android.content.Context;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;


import com.anyonavinfo.cpaddemo.R;
import com.anyonavinfo.cpaddemo.data.appinfo.AppInfo;
import com.anyonavinfo.cpaddemo.utils.AppManagerUtils;
import com.anyonavinfo.cpaddemo.view.widget.dynamicgrid.BaseDynamicGridAdapter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by ZuiC on 2017/1/19.
 */

public class AppDynamicAdapter extends BaseDynamicGridAdapter {

    private static final String[] sPosition = {
            "1", "2", "3", "4", "5", "6", "7", "8", "9"
    };

    private Map<String, AppInfo> appPositionInfo = new LinkedHashMap<>();

    private List<Integer> mAppIcon;



    public AppDynamicAdapter(Context context, List<AppInfo> appInfoList, int columnCount) {
        super(context, new ArrayList<Object>(Arrays.asList(sPosition)), columnCount);
        for (int i = 0; i < appInfoList.size(); i++){
            appPositionInfo.put(sPosition[i], appInfoList.get(i));
        }

        for (int i = 0; i < 9 - appInfoList.size(); i++){
            appPositionInfo.put(sPosition[i + appInfoList.size()], new AppInfo("NULL", "NULL", "NULL", "NULL" , -1 , -1 ,false));
        }
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        AppViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_gv_appicon, null);
            holder = new AppViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (AppViewHolder) convertView.getTag();
        }
        holder.build(getItem(position).toString());
        return convertView;
    }


    private class AppViewHolder implements View.OnClickListener{

        private ImageView ivAppIcon;
        private String appPosition;
        private String appPackageName;

        private AppViewHolder(View view){
            ivAppIcon = (ImageView) view.findViewById(R.id.app_icon_iv);
            ivAppIcon.setOnClickListener(this);
        }

        void build(String position){
            AppInfo appInfo = appPositionInfo.get(position);
            if (!appInfo.getAppPackageName().equals("NULL")){
                ivAppIcon.setImageResource(appInfo.getAppIcon());
            }else {
                ivAppIcon.setImageResource(R.drawable.icon_blank);
            }
            appPosition = position;
            appPackageName = appInfo.getAppPackageName();
        }

        @Override
        public void onClick(View v) {
            if (!appPackageName.equals("NULL")){
                AppManagerUtils.getInstance().launchActivity(appPackageName);
            }
        }
    }
}
